package jpush

import (
	"bytes"
	"encoding/json"
	"strconv"
)

func (c *Client) PushToAndroid(registrationId string, title string, content string, extra map[string]any) (map[string]any, error) {
	req := &PushRequest{
		// Cid:      uuid.NewV4().String(),
		Platform: PlatformAndroid,
		Audience: &PushAudience{
			RegistrationId: []string{registrationId},
		},
		Notification: &PushNotification{
			Android: &NotificationAndroid{
				Alert:     content,
				Title:     title,
				Priority:  1,
				AlertType: -1,
				Extras:    extra,
			},
		},
		Options: &PushOptions{
			TimeToLive: 60,
		},
	}
	return c.Push(req)
}
func (c *Client) PushToIOS(registrationId string, title string, content string, extra map[string]any) (map[string]any, error) {
	req := &PushRequest{
		//Cid:      uuid.NewV4().String(),
		Platform: PlatformIOS,
		Audience: &PushAudience{
			RegistrationId: []string{registrationId},
		},
		Notification: &PushNotification{
			IOS: &NotificationIOS{
				Alert:  content,
				Sound:  "default",
				Extras: extra,
			},
		},
		Options: &PushOptions{
			TimeToLive: 60,
		},
	}
	return c.Push(req)
}

func (c *Client) Push(push *PushRequest) (map[string]any, error) {
	link := c.pushUrl + "/v3/push"
	buf, err := json.Marshal(push)
	if err != nil {
		return nil, err
	}
	resp, err := c.request("POST", link, bytes.NewReader(buf), false)
	if err != nil {
		return nil, err
	}
	return resp.Map()
}

func (c *Client) GetCidPool(count int, cidType string) (map[string]any, error) {
	link := c.pushUrl + "/v3/push/cid?"
	if count > 0 {
		link += "count=" + strconv.Itoa(count)
	}
	if cidType != "" {
		link += "type=" + cidType
	}
	resp, err := c.request("GET", link, nil, false)
	if err != nil {
		return nil, err
	}
	return resp.Map()
}

func (c *Client) GroupPush(push *PushRequest) (map[string]any, error) {
	link := c.pushUrl + "/v3/grouppush"
	buf, err := json.Marshal(push)
	if err != nil {
		return nil, err
	}
	resp, err := c.request("POST", link, bytes.NewReader(buf), true)
	if err != nil {
		return nil, err
	}
	return resp.Map()
}

func (c *Client) Validate(req *PushRequest) (map[string]any, error) {
	link := c.pushUrl + "/v3/push/validate"
	buf, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	resp, err := c.request("POST", link, bytes.NewReader(buf), false)
	if err != nil {
		return nil, err
	}
	return resp.Map()
}
